<template>
    <div class="categories">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>商品分类</el-breadcrumb-item>
      </el-breadcrumb>
      <div class="container">

        <div class="addbox">
          <el-button type="primary" @click="addCateVisible = true">添加分类</el-button>
          <el-dialog v-model="addCateVisible" title="添加分类">
            <el-form
              :model="addCateFrom"
              :label-width="100"
              class="demo-ruleForm"
              ref="addCateFromref"
              :rules="addrules"
            >
              <el-form-item label="分类名称" prop="name">
                <el-input v-model="addCateFrom.name" type="text" />
              </el-form-item>

              <el-form-item label="父级分类" prop="details">
                <el-cascader
                  placeholder="请选择分类"
                  v-model="addCateFrom.catename"
                  :options="cascader"
                  :props="cascaderprops"
                  @change="handleChange"
                />
              </el-form-item>

              <el-form-item>
                <el-button @click="addCateVisible = false">取消</el-button>
                <el-button type="primary" @click="addCateOK(addCateFromref)">确定</el-button>
              </el-form-item>
            </el-form>
          </el-dialog>

        </div>
        <div class="titlebox">
          <el-alert
            title="下来的数据只要多一点,eltable就会光速爆炸,渲染巨慢,所以建议一次只看一行,获得流畅体验"
            type="warning"
            effect="dark"
            show-icon
          />
        </div>
        <el-table
          :data="CateGoryList"
          style="width: 100%"
          border
          stripe
          size="default"
          row-key="cat_id"
          :load="load"
          lazy
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        >
          <el-table-column prop="index" width="60" />
          <el-table-column prop="cat_name" label="分类名称" />
          <el-table-column prop="cat_deleted" label="是否有效">
            <template #default="scope">
              <el-tag type="success" round effect="dark" v-if="!scope.row.is_ok">有效</el-tag>
              <el-tag type="error" round effect="dark" v-else>无效</el-tag>
            </template>
          </el-table-column>
  
          <el-table-column prop="cat_level" label="排序">
            <template #default="scope">
              <el-tag
                :type="levelfiltertwo[scope.row.cat_level].type"
              >{{levelfiltertwo[scope.row.cat_level].text}}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="operation" label="操作">
            <template #default="scope">
              <el-button type="primary" @click="edit(scope.row)">
                <el-icon>
                  <EditPen />
                </el-icon>编辑
              </el-button>
              <el-button type="danger" @click="deleteThere(scope.row)">
                <el-icon>
                  <Delete />
                </el-icon>删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination">
          <el-config-provider :locale="zhCn">
            <el-pagination
              v-model:current-page="queryInfo.pagenum"
              v-model:page-size="queryInfo.pagesize"
              :page-sizes="[1,2, 3, 5]"
              layout="total,sizes, prev, pager, next, jumper"
              :total="totals"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </el-config-provider>
        </div>
        <el-dialog v-model="editVisible" title="修改用户信息">
          <el-form
            :model="editFrom"
            :label-width="100"
            class="demo-ruleForm"
            :rules="addrules"
            ref="editFromref"
          >
            <el-form-item label="分类名称" prop="catename">
              <el-input v-model="editFrom.catename" type="text" />
            </el-form-item>
            <el-form-item>
              <el-button @click="editVisible = false">取消</el-button>
              <el-button type="primary" @click="editThere(editFromref)">确定</el-button>
            </el-form-item>
          </el-form>
        </el-dialog>
      </div>
    </div>
  </template>
  <script setup>
  import { reactive, ref, onBeforeMount } from "vue";
  import zhCn from "element-plus/lib/locale/lang/zh-cn";
  import { useRoute, useRouter } from "vue-router";
  import { ElMessage, ElMessageBox } from "element-plus";
  import {
    getCategories,
    deleteCategories,
    postaddCategories,
    puteditCategories
  } from "../tools/ajax.js";
  import { levelfiltertwo } from "../tools/filiter.js";
  const route = useRoute();
  const router = useRouter();
  const cascaderprops = {
    expandTrigger: "hover",
    label: "cat_name",
    value: "cat_level",
    children: "children",
    emitPath: false
  };
  const cascader = reactive([]);
  const editFromref = reactive({});
  const CateGoryList = reactive([]);
  const editVisible = ref(false);
  const addCateVisible = ref(false);
  const editFrom = reactive({
    catename: "",
    id: ""
  });
  const addCateFromref = reactive({});
  const addCateFrom = reactive({
    name: "",
    catename: 0
  });
  const queryInfo = reactive({
    type: "",
    pagenum: 1,
    pagesize: 1
  });
  const totals = ref(0);
  const load = (row, treeNode, resolve) => {
    console.log(row, treeNode);
    if (row.cat_level == 0) {
      row.children.forEach(item => {
        if (item.children.length >= 1) {
          item.hasChildren = true;
          setTimeout(() => {
            resolve(row.children);
          }, 500);
        }
      });
    } else if (row.cat_level == 1) {
      setTimeout(() => {
        resolve(row.children);
      }, 500);
    }
  };
  const addrules = {
    catesname: [
      {
        required: true,
        message: "分类名称不能为空",
        trigger: "change"
      }
    ],
    name: {
      required: true,
      message: "分类名称不能为空",
      trigger: "change"
    }
  };
  function getlist() {
    getCategories({ params: queryInfo }).then(res => {
      console.log(res.data);
      totals.value = res.data.total;
      CateGoryList.splice(0, 1000);
      CateGoryList.push(...res.data.result);
      CateGoryList.forEach((item, i) => {
        item.index = i + 1;
        item.hasChildren = true;
      });
    });
  }
  function getTypeList() {
    getCategories({ params: { type: 2 } }).then(res => {
      console.log(res);
      cascader.splice(0, 1000);
      cascader.push(...res.data);
    });
  }
  function toAddGoods() {
    router.push("/goods/all");
  }
  function handleSizeChange() {
    console.log("条数改变了");
    getlist();
  }
  function handleCurrentChange() {
    console.log("翻页");
    getlist();
  }
  function search() {
    console.log("搜索");
    getlist();
  }
  
  function editThere(from) {
    from.validate(flag => {
      if (flag) {
        console.log(editFrom);
        puteditCategories({
          id: editFrom.id,
          cat_name: editFrom.catename
        }).then(res => {
          console.log(res);
          if (res.meta.status == 200) {
            ElMessage.success(res.meta.msg);
            editVisible.value = false;
            getlist();
          } else {
            ElMessage.error(res.meta.msg);
          }
        });
      } else {
        return;
      }
    });
  }
  function edit(item) {
    console.log(item);
    editVisible.value = true;
    editFrom.catename = item.cat_name;
    editFrom.id = item.cat_id;
  }
  function deleteThere(item) {
    console.log(item.cat_id);
    ElMessageBox.confirm("此操作将永久删除该分类,是否继续?", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    })
      .then(() => {
        deleteCategories({ id: item.id }).then(res => {
          console.log(res);
          if (res.meta.status == 200) {
            getlist();
            ElMessage.success(res.meta.msg);
          } else {
            ElMessage.error(res.meta.msg);
          }
        });
      })
      .catch(() => {
        ElMessage.warning("取消 删除");
      });
  }
  
  function addCateOK(from) {
    from.validate(flag => {
      if (flag) {
        console.log(addCateFrom);
        postaddCategories({
          cat_name: addCateFrom.name,
          roleDesc: addCateFrom.details
        }).then(res => {
          console.log(res);
          if (res.meta.status == 201) {
            ElMessage.success(res.meta.msg);
            getlist();
          } else {
            ElMessage.error(res.meta.msg);
          }
        });
        addCateVisible.value = false;
      } else {
        return;
      }
    });
  }
  const handleChange = value => {
    console.log(value);
  };
  onBeforeMount(() => {
    getlist();
    getTypeList();
  });
  </script>
  
  <style scoped>
  .addbox {
    display: flex;
    margin-bottom: 20px;
  }
  .pagination {
    margin-top: 20px;
  }
  .titlebox{
    margin-bottom: 30px;
  }
  </style>